<?php

class DocumentController extends Controller
{
	var $arr_role = array();
	var $role_index =  array();
	var $role_create =  array();
	var $role_update = array();
	var $role_view = array();
	var $role_delete = array();
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		$role = UserRole::model()->findAllByAttributes(array('userID'=>Yii::app()->user->id));
		foreach($role as $i) {
			array_push($this->arr_role, $i->roleID);
		} 
		
		$controllerID = AdminController::model()->findByAttributes(array('controller'=>'document'))->ID;
		
		$index = AdminAction::model()->findByAttributes(array('controllerID'=>$controllerID,'action'=>'index'))->ID;
		$arr_index = AdminPermission::model()->findAllByAttributes(array('actionID'=>$index));
		foreach($arr_index as $i) {
			array_push($this->role_index, $i->roleID);
		}
		
		$create = AdminAction::model()->findByAttributes(array('controllerID'=>$controllerID,'action'=>'create'))->ID;
		$arr_create = AdminPermission::model()->findAllByAttributes(array('actionID'=>$create));
		foreach($arr_create as $i) {
			array_push($this->role_create, $i->roleID);
		}
		
		$update = AdminAction::model()->findByAttributes(array('controllerID'=>$controllerID,'action'=>'update'))->ID;
		$arr_update = AdminPermission::model()->findAllByAttributes(array('actionID'=>$update));
		foreach($arr_update as $i) {
			array_push($this->role_update, $i->roleID);
		}
		
		$view = AdminAction::model()->findByAttributes(array('controllerID'=>$controllerID,'action'=>'view'))->ID;
		$arr_view = AdminPermission::model()->findAllByAttributes(array('actionID'=>$view));
		foreach($arr_view as $i) {
			array_push($this->role_view, $i->roleID);
		}
		
		$delete = AdminAction::model()->findByAttributes(array('controllerID'=>$controllerID,'action'=>'delete'))->ID;
		$arr_delete = AdminPermission::model()->findAllByAttributes(array('actionID'=>$delete));
		foreach($arr_delete as $i) {
			array_push($this->role_delete, $i->roleID);
		}
		return array(
			array('allow',  
				'actions'=>array('index'),
				'users'=>array('@'),
				'expression'=>'count(array_intersect(yii::app()->controller->role_index,yii::app()->controller->arr_role))>0'
			),
			array('allow',
				'actions'=>array('create','LoadTopicAjax'),
				'users'=>array('@'),
				'expression'=>'count(array_intersect(yii::app()->controller->role_create,yii::app()->controller->arr_role))>0'
			),
			array('allow',
				'actions'=>array('update','LoadTopicAjax','removeimage'),
				'users'=>array('@'),
				'expression'=>'count(array_intersect(yii::app()->controller->role_update,yii::app()->controller->arr_role))>0'
			),
			array('allow',
				'actions'=>array('view'),
				'users'=>array('@'),
				'expression'=>'count(array_intersect(yii::app()->controller->role_view,yii::app()->controller->arr_role))>0'
			),
			array('allow',
				'actions'=>array('delete'),
				'users'=>array('@'),
				'expression'=>'count(array_intersect(yii::app()->controller->role_delete,yii::app()->controller->arr_role))>0'
			),	
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
	  $file = Document::model()->getPhoto($id);
    $photo = Yii::app()->baseUrl."/upload/document/thumbs_100x100/".$file;
    if($file=="") {
      $photo = Yii::app()->baseUrl."/images/no-image.jpg";
    }
		$this->render('view',array(
			'model'=>$this->loadModel($id), 'photo'=>$photo
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Document;

		if(isset($_POST['Document']))
		{
			$model->attributes=$_POST['Document'];
			$model->topicID=$_POST['Document']['topicID'];
		  if($model->validate()) {
		    if(CUploadedFile::getInstanceByName('Document[photo]')) {
		      $file = new File();
		      $photo = CUploadedFile::getInstanceByName('Document[photo]');
		      $file->filename = $photo->getName();
		    	$file->filesaved = encodeFilename(time().'_'.$photo->getName());
		    	$file->filetype =  $photo->getType();
		    	$file->folder = 'document';
		    	$photo->saveAs('upload/document/'.$file->filesaved);
		    	$file->save();
		    	$model->photo = $file->ID;
		    	//thumbnail
		    	$thumb = Yii::app()->image->load(Yii::getPathOfAlias("webroot")."/upload/document/".$file->filesaved);
		    	$thumb->resize(100, 100);
		    	$thumb->save(Yii::getPathOfAlias("webroot")."/upload/document/thumbs_100x100/".$file->filesaved);//save vao thumb
		    }
		    $model->save();
        Yii::app()->user->setFlash('success',"Tạo mới thành công");			  
				$this->redirect(array('view','id'=>$model->ID));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
    $file_photo = Document::model()->getPhoto($id);
    $img = "";
		if(isset($_POST['Document']))
		{
			$model->attributes=$_POST['Document'];
			$model->topicID=$_POST['Document']['topicID'];
		  if($model->validate()) {
		    if(CUploadedFile::getInstanceByName('Document[photo]')) {
		      if($file_photo!="") {
		        $f = File::model()->findByAttributes(array('filesaved'=>$file_photo));
		        if(!empty($f)) {
		          if(file_exists(Yii::app()->basePath.'/../upload/document/'.$file_photo)) {
		            @unlink(Yii::getPathOfAlias("webroot").'/upload/document/'.$file_photo);
		          }
		          if(file_exists(Yii::app()->basePath.'/../upload/document/thumbs_100x100/'.$file_photo)) {
		            @unlink(Yii::getPathOfAlias("webroot").'/upload/document/thumbs_100x100/'.$file_photo);
		          }
		          $f->delete();
		        }
		      }
		      $file = new File();
		      $photo = CUploadedFile::getInstanceByName('Document[photo]');
		      $file->filename = $photo->getName();
		    	$file->filesaved = encodeFilename(time().'_'.$photo->getName());
		    	$file->filetype =  $photo->getType();
		    	$file->folder = 'document';
		    	$photo->saveAs('upload/document/'.$file->filesaved);
		    	$file->save();
		    	$model->photo = $file->ID;
		    	//thumbnail
		    	$thumb = Yii::app()->image->load(Yii::getPathOfAlias("webroot")."/upload/document/".$file->filesaved);
		    	$thumb->resize(100, 100);
		    	$thumb->save(Yii::getPathOfAlias("webroot")."/upload/document/thumbs_100x100/".$file->filesaved);//save vao thumb
		    }
		    $model->save();
        Yii::app()->user->setFlash('success',"Cập nhật thành công");			  
				$this->redirect(array('view','id'=>$model->ID));
			}
		}
	  if(!empty($file_photo)) {
      $img = Yii::app()->baseUrl."/upload/document/thumbs_100x100/".$file_photo;
    }
		$this->render('update',array(
			'model'=>$model, 'img'=>$img
		));
	}
  /**
   * LoadTopicAjax
   * @author K.D
   */
	public function actionLoadTopicAjax()
	{
	  if(Yii::app()->request->isAjaxRequest) {
	    $subjectID = $_POST['subjectID'];
	    $topic = Topic::model()->getListTopic($subjectID);
	    if(!empty($topic)) {
	      $string = CHtml::dropDownList('Document[topicID]', '', Topic::model()->getListTopic($subjectID));
	    }
	    echo json_encode(array('result'=>'success','html'=>$string));
	  }
	}
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			$model->deleted = 1;
			$model->update();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

  public function actionIndex()
	{
		$model=new Document('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Document'])) {
			$model->attributes=$_GET['Document'];
			$model->topicID=$_GET['Document']['topicID'];
		}
		$this->render('index',array(
			'model'=>$model,
		));
	}
/**
   * Remove photo of document
   * @author K.D
   */
	public function actionRemoveImage() {
	  if(Yii::app()->request->isAjaxRequest) {
	    $ID = isset($_POST['ID'])?$_POST['ID']:"";
	    $model = $this->loadModel($ID);
	    if(!empty($model)) {
	      $file = File::model()->findByPk($model->photo);
	      if(!empty($file)) {
	        if(file_exists(Yii::app()->basePath.'/../upload/document/'.$file->filesaved)) {
	          @unlink(Yii::getPathOfAlias("webroot").'/upload/document/'.$file->filesaved);
	        }
	        if(file_exists(Yii::app()->basePath.'/../upload/document/thumbs_100x100/'.$file->filesaved)) {
	          @unlink(Yii::getPathOfAlias("webroot").'/upload/document/thumbs_100x100/'.$file->filesaved);
	        }
	        $file->delete();
	      }
	      $model->photo = 0;
	      $model->update();
	      
	      echo "success";
	    }
	  }
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Document::model()->findByAttributes(array('ID'=>$id,'deleted'=>0));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='document-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
